package cn.tedu._05mvcboot03.controller;


import cn.tedu._05mvcboot03.base.response.JsonResult;
import cn.tedu._05mvcboot03.base.response.StatusCode;
import cn.tedu._05mvcboot03.mapper.MvcUserMapper;
import cn.tedu._05mvcboot03.pojo.dto.UserArticleDTO;
import cn.tedu._05mvcboot03.pojo.dto.UserLoginDTO;
import cn.tedu._05mvcboot03.pojo.entity.MvcArticle;
import cn.tedu._05mvcboot03.pojo.vo.ArticleVO;
import cn.tedu._05mvcboot03.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@Validated
@Api(tags = "用户模块")
@RequestMapping("/v1/users/")
public class MvcUserController {

    @Autowired
    private MvcUserMapper mvcUserMapper;

    @PostMapping("login")
    @ApiOperation(value = "登录功能")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession httpSession){
        log.debug("userLoginDTO = {}",userLoginDTO);
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        UserVO userVO = mvcUserMapper.selectUser(username, password);
        if (userVO == null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        httpSession.setAttribute("user",userVO);
        return new JsonResult(StatusCode.OPERATION_SUCCESS,userVO);

    }

    @PostMapping("article")
    @ApiOperation(value = "发表文章功能")
    public JsonResult article(@RequestBody @Validated UserArticleDTO userArticleDTO, @ApiIgnore HttpSession httpSession){
        log.debug("userArticleDTO = {}",userArticleDTO);
        UserVO userVO = (UserVO) httpSession.getAttribute("user");
        MvcArticle mvcArticle = new MvcArticle();
        BeanUtils.copyProperties(userArticleDTO,mvcArticle);
        mvcArticle.setUserId(userVO.getId());
        mvcUserMapper.article(mvcArticle);
        return JsonResult.ok();

    }

    @GetMapping("selectByArticleId")
    @ApiOperation(value = "查询指定文章功能")
    @ApiImplicitParam(name = "id",value = "文章ID",required = true,dataType = "int")
    public JsonResult selectByArticleId(@Range(min = 1,max = 100,message = "文章ID要求在1-100之间") @RequestParam Long id){
        log.debug("id = {}" , id);
        ArticleVO articleVO = mvcUserMapper.selectByArticleId(id);
        return JsonResult.ok(articleVO);

    }


}
